#pragma execution_character_set("utf-8")
#include "dragpushbutton.h"
#include "macro.h"
#include <qmath.h>

QPoint DragPushButton::pressPoint;
int DragPushButton::i0 = 0;
int DragPushButton::j0 = 0;

DragPushButton::DragPushButton(QWidget* parent)
    : QPushButton(parent)
{
}

void DragPushButton::setIJ(int i, int j)
{
    this->i = i;
    this->j = j;
}

void DragPushButton::mousePressEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton) {
        this->raise(); //将此按钮移动到顶层显示
        pressPoint = event->pos();
        j0 = (this->mapToParent(pressPoint).x() - GAME_FIELD_X) / BLOCK_EDGE;
        i0 = (this->mapToParent(pressPoint).y() - GAME_FIELD_Y) / BLOCK_EDGE;

        // qDebug() << event;
        // qDebug() << "set i0=" << i0 << ", j=" << j0;
    }
}

void DragPushButton::mouseReleaseEvent(QMouseEvent* event)
{

    int x = this->geometry().x(),
        y = this->geometry().y();

    this->setGeometry(
        GAME_FIELD_X + BLOCK_EDGE * this->j + BLOCK_MARGIN,
        GAME_FIELD_Y + BLOCK_EDGE * this->i + BLOCK_MARGIN,
        BLOCK_EDGE - BLOCK_MARGIN * 2,
        BLOCK_EDGE - BLOCK_MARGIN * 2);

    // qDebug() << event;
    // qDebug() << "x=" << x << ", y=" << y;

    // 落点在方块区域内有效
    if (x > GAME_FIELD_X && x < GAME_FIELD_X + ROW_SIZE * BLOCK_EDGE && y > GAME_FIELD_Y && y < GAME_FIELD_Y + COL_SIZE * BLOCK_EDGE) {
        int j1 = (x - GAME_FIELD_X) / BLOCK_EDGE;
        int i1 = (y - GAME_FIELD_Y) / BLOCK_EDGE;

        // qDebug() << "i1=" << i0 << ", j1=" << j0 << ", i2=" << i1 << ", j2=" << j1 << endl;

        // 未发生移动
        if (i0 == i1 && j0 == j1)
            return;

        // 仅允许沿着一个方向移动一格
        if ((i0 == i1 && abs(j0 - j1) <= 1) || (j0 == j1 && abs(i0 - i1) <= 1)) {
            // qDebug() << "emit switchBlock";
            emit swapBlockSig(i0, j0, i1, j1);
        }
    }
}

void DragPushButton::mouseMoveEvent(QMouseEvent* event)
{
    if (event->buttons() == Qt::LeftButton) {
        this->move(this->mapToParent(event->pos() - DragPushButton::pressPoint));

        //防止按钮移出父窗口
        if (this->mapToParent(this->rect().topLeft()).x() <= 0) {
            this->move(0, this->pos().y());
        }
        if (this->mapToParent(this->rect().bottomRight()).x() >= this->parentWidget()->rect().width()) {
            this->move(this->parentWidget()->rect().width() - this->width(), this->pos().y());
        }
        if (this->mapToParent(this->rect().topLeft()).y() <= 0) {
            this->move(this->pos().x(), 0);
        }
        if (this->mapToParent(this->rect().bottomRight()).y() >= this->parentWidget()->rect().height()) {
            this->move(this->pos().x(), this->parentWidget()->rect().height() - this->height());
        }
    }
}
